function toUint8Array(wordArray) {
  // Shortcuts
  const words = wordArray.words;
  const sigBytes = wordArray.sigBytes;

  // Convert
  const u8 = new Uint8Array(sigBytes);
  for (let i = 0; i < sigBytes; i++) {
    u8[i] = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  }
  return u8;
}

function Uint8ArrayToString(fileData) {
  let dataString = '';
  for (let i = 0; i < fileData.length; i++) {
    dataString += String.fromCharCode(fileData[i]);
  }
  return dataString;
}
// 签名函数示例
function signCallback(signStr) {
  const secretKey = config.secretKey;
  const hash = window.CryptoJSTest.HmacSHA1(signStr, secretKey);
  const bytes = Uint8ArrayToString(toUint8Array(hash));
  return window.btoa(bytes);
}

let config = {
  secretKey: 'uQb48a48hbGIrpe73CaYeMV8HwedIAon',
  secretId: 'AKIDMDaeys72TN14j7bhfBBlrZu7p1pJvpZz',
  appId: 1251008584,
}

import WebAudioSpeechRecognizer from './webaudiospeechrecognizer';

export default class RadioWsUtil {
  constructor() {

  }

  setRecChange(func) {
    this.onRecChange = func;
  }

  setRecEnd(func) {
    this.onRecEnd = func;
  }

  setRecStop(func) {
    this.onRecStop = func;
  }

  init() {
    this.speechRecognizer.OnRecognitionResultChange = (res) => {
      // console.log('识别变化时', res);
      if (this.onRecChange != undefined) {
        this.onRecChange(res);
      }
    };
    // 一句话结束
    this.speechRecognizer.OnSentenceEnd = (res) => {
      // console.log('一句话结束', res);
      if (this.onRecEnd != undefined) {
        this.onRecEnd(res);
      }
    };
    // 识别结束
    this.speechRecognizer.OnRecognitionComplete = (res) => {
      // console.log('识别结束', res);
      if (this.onRecStop != undefined) {
        this.onRecStop(res);
      }
    };
  }

  start() {
    const params = {
      signCallback: signCallback, // 鉴权函数
      // 用户参数
      secretid: config.secretId,
      appid: config.appId,
      // 实时识别接口参数
      engine_model_type: '16k_zh', // 因为内置WebRecorder采样16k的数据，所以参数 engineModelType 需要选择16k的引擎，为 '16k_zh'
      // 以下为非必填参数，可跟据业务自行修改
      voice_format: 1,
      hotword_id: '08003a00000000000000000000000000',
      needvad: 1,
      filter_dirty: 1,
      filter_modal: 2,
      filter_punc: 0,
      convert_num_mode: 1,
      word_info: 2
    }
    this.speechRecognizer = new WebAudioSpeechRecognizer(params);
    this.init();
    this.speechRecognizer.start();
  }

  stop() {
    this.speechRecognizer.stop();
  }
}